import {PageContainer} from "@ant-design/pro-layout";
import type {ActionType, ProColumns} from "@ant-design/pro-table";
import ProTable from "@ant-design/pro-table";
import {StatusEnum} from "@/services/abis/enum";
import {Button, Form, message, Popconfirm, Space} from "antd";
import {addRole, delRole, editRole, flushStatus, getRole} from "@/services/abis/role";
import {useRef, useState} from "react";
import type {ProFormInstance} from "@ant-design/pro-form";
import {ModalForm, ProFormGroup, ProFormText} from "@ant-design/pro-form";
import {PlusOutlined} from "@ant-design/icons";
import {green, orange, red} from "@ant-design/colors";
import {parseAccountList} from "@/utils/handle";


export default () => {
  const [modalVisit, setModalVisit] = useState<boolean>(false)
  const [isEdit, setIsEdit] = useState<boolean>(false)
  const ref = useRef<ActionType>()
  const formRef = useRef<ProFormInstance>()

  const batchDelete = (id: (number | string)[]) => {
    delRole(id)
      .then(() => {
        ref.current?.clearSelected!()
        message.success("删除角色成功")
      })
      .finally( () => ref.current?.reload())
  }

  const batchStatus = (id: (number | string)[], status: number = 0) => {
    flushStatus(id, status)
      .then( () => {
        message.success(status === 0 ? '禁用角色成功' : '启用角色成功')
      })
      .catch( () => {
        message.warn(status === 0 ? '禁用角色失败' : '启用角色失败')
      })
      .finally( () => ref.current?.reload() )
  }

  const columns: ProColumns<ABIS.RoleVO>[] = [
    {
      title: '序号',
      dataIndex: 'id',
      valueType: 'index'
    },
    {
      title: '角色',
      dataIndex: 'role',
      order: 6
    },
    {
      title: '角色名',
      dataIndex: 'label',
      order: 5
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: StatusEnum,
      search: false,
      filters: true,
      onFilter: false
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      valueType: 'dateTimeRange',
      order: 2,
      sorter: true,
      search: {
        transform: value => {
          return {
            created_start_at: value[0],
            created_end_at: value[1]
          }
        }
      },
      render: (_, record) => {
        return record.created_at.replace('T', ' ')
      }
    },
    {
      title: '创建人',
      dataIndex: 'created_by_name',
      valueType: 'select',
      order: 4,
      fieldProps: {
        showSearch: true
      },
      request: parseAccountList,
      search: {
        transform: value => {
          return {
            'created_by': value
          }
        }
      },
      render: (value, record) => {
        return record.created_by == 0 ? '系统' : value
      }
    },
    {
      title: '更新时间',
      dataIndex: 'updated_at',
      valueType: 'dateTimeRange',
      order: 1,
      sorter: true,
      search: {
        transform: value => {
          return {
            updated_start_at: value[0],
            updated_end_at: value[1]
          }
        }
      },
      render: (_, record) => {
        return record.updated_at ? record.updated_at.replace('T', ' ') : '-'
      },
    },
    {
      title: '更新人',
      dataIndex: 'updated_by_name',
      valueType: 'select',
      order: 3,
      fieldProps: {
        showSearch: true
      },
      request: parseAccountList,
      search: {
        transform: value => {
          return {
            'updated_by': value
          }
        }
      }
    },
    {
      title: '操作',
      valueType: "option",
      width: 160,
      render: (_, record) => record.role !== 'super-admin' && [
        <a key="edit" onClick={() => {
          setIsEdit(true)
          setModalVisit(true)
          formRef.current?.setFieldsValue(record)
        }}>编辑</a>,
        record.status === 1 ?
          <a key="disable" style={{color: orange.primary}} onClick={() => {
            batchStatus([record.id])
          }}>禁用</a> :
          <a key="enable" style={{color: green.primary}} onClick={() => {
            batchStatus([record.id], 1)
          }}>启用</a>,
        <Popconfirm
          key="delete"
          title="您确认要删除?删除后不可恢复"
          onConfirm={() => {
            batchDelete([record.id])
          }}
        >
          <a style={{color: red.primary}}>删除</a>
        </Popconfirm>,
      ]
    }
  ]


  return (
    <>
      <PageContainer>
        <ProTable<ABIS.RoleVO>
          cardBordered={true}
          columns={columns}
          actionRef={ref}
          rowKey={record => record.id}
          toolbar={{
            actions: [
              <Button type="primary" icon={<PlusOutlined/>} onClick={() => {
                setModalVisit(true)
                setIsEdit(false)
              }}>新建角色</Button>,
              <ModalForm<ABIS.Role>
                title={isEdit ? '编辑角色' : '新建角色'}
                visible={modalVisit}
                formRef={formRef}
                isKeyPressSubmit
                autoFocusFirstInput
                modalProps={{
                  destroyOnClose: true
                }}
                onFinish={async (formData) => {
                  if (isEdit) {
                    const {code} = await editRole(formData.id, formData.label, formData.role)
                    if (code === 1000) message.success('编辑角色成功')
                    else message.success("编辑角色失败")
                  } else {
                    const result = await addRole(formData.label, formData.role)
                    if (result.code === 1000) message.success('新增角色成功')
                    else message.warn(result.message)
                  }
                  setModalVisit(false)
                  ref.current?.reload()
                }}
                onVisibleChange={visible => {
                  if (!visible) {
                    setModalVisit(false)
                  }
                }}
              >
                <ProFormGroup>
                  <ProFormText label="角色" name="role" width="md" required
                               rules={[{required: true, message: '角色不能为空'}]}/>
                  <ProFormText label="角色名" name="label" width="md" required
                               rules={[{required: true, message: '角色名不能为空'}]}/>
                  <Form.Item name="id">
                    <input hidden/>
                  </Form.Item>
                </ProFormGroup>
              </ModalForm>
            ]
          }}
          request={async (params, sort, filter) => {

            const {data: roles} = await getRole({...params, ...sort, ...(filter.status ? filter : {})})
            return {
              data: roles.list,
              success: true,
              total: roles.total
            }
          }}
          rowSelection={{
            preserveSelectedRowKeys: true,
            getCheckboxProps: record => {
              const disabled = record.role === 'super-admin'
              return {disabled: disabled}
            }
          }}
          tableAlertOptionRender={({selectedRowKeys, onCleanSelected}) => {
            return (
              <Space size={16}>
                <a onClick={onCleanSelected}>取消选择</a>
                <a style={{color: orange.primary}} onClick={ () => {
                  batchStatus(selectedRowKeys)
                } }>批量禁用</a>
                <a style={{color: green.primary}} onClick={ () => {
                  batchStatus(selectedRowKeys, 1)
                } }>批量启用</a>
                <Popconfirm
                  key="delete"
                  title="您确认要删除?删除后不可恢复"
                  onConfirm={() => {
                    batchDelete(selectedRowKeys)
                  }}
                >
                  <a style={{color: red.primary}}>批量删除</a>
                </Popconfirm>
              </Space>
            )
          }}
          pagination={{
            hideOnSinglePage: true
          }}
        />
      </PageContainer>
    </>
  )
}
